package com.lottery.im.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lottery.im.R;
import com.lottery.im.module.chat.ui.NewFragmentActivity;
import com.lottery.im.widget.NoScrollGridView;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 资金密码输入
 */
public class PassValidationDialogBuilder extends Dialog implements View.OnClickListener,
    AdapterView.OnItemClickListener {

  private static Context tmpContext;
  private static PassValidationDialogBuilder instance;

  private View mDialogView;
  private RelativeLayout mLayoutAll;

  private Stack<Integer> mNumberStack;//保存输入的数字
  private List<TextView> mNumberViewList;//保存密码显示的几个text
  private final static int NUMBER_BUTTON_DELETE = 11; //删除键
  private final static int NUMBER_BUTTON_ZERO = 10;//0号按键
  private final static int NUMBER_BUTTON_CLEAR = 9;//清除按键
  private final static int NUMBER_COUNT = 6;

  private TextView mNumber1TextView;
  private TextView mNumber2TextView;
  private TextView mNumber3TextView;
  private TextView mNumber4TextView;
  private TextView mNumber5TextView;
  private TextView mNumber6TextView;
  private NoScrollGridView mNumbersGridView; // 密码gridView
  private NumberAdapter mNumberAdapter;    // 数字adapter
  private boolean mIsPassword = true;
  private final static String PASSWORD_NUMBER_SYMBOL = "●";

  private ImageView ivLeft;
  private TextView tvTitle;

  private OnInputNumberCodeCallback mCallback; // 返回结果的回调

  public PassValidationDialogBuilder(Context context) {
    super(context);
    init(context);
  }

  public PassValidationDialogBuilder(Context context, int theme) {
    super(context, theme);
    init(context);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    getWindow().setAttributes(params);
    setCancelable(true);
    setCanceledOnTouchOutside(true);
  }

  public static PassValidationDialogBuilder getInstance(Context context) {

    if (instance == null || !tmpContext.equals(context)) {
      synchronized (ConfirmWarnDialogBuilder.class) {
        if (instance == null || !tmpContext.equals(context)) {
          instance = new PassValidationDialogBuilder(context, R.style.dialog_untran);
        }
      }
    }
    tmpContext = context;
    return instance;
  }

  private void init(Context context) {

    mDialogView = View.inflate(context, R.layout.dialog_pass_valitation, null);
    mLayoutAll = mDialogView.findViewById(R.id.layout_all);

    setContentView(mDialogView);

    mLayoutAll.setOnClickListener(view -> dismiss());

    mDialogView.findViewById(R.id.layout_dialog).setOnClickListener(view -> {
    });

    mDialogView.findViewById(R.id.tv_forget_password)
        .setOnClickListener(view -> {
          NewFragmentActivity.create(tmpContext,
              NewFragmentActivity.FragmentInfoType.FORGETMONEYPWD);
          dismiss();
        });

    mNumberStack = new Stack<>();
    mNumberViewList = new ArrayList<>();
    mNumberAdapter = new NumberAdapter(getContext());

    LayoutInflater inflater =
        (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mNumber1TextView = mDialogView.findViewById(R.id.number_1_textView);
    mNumber2TextView = mDialogView.findViewById(R.id.number_2_textView);
    mNumber3TextView = mDialogView.findViewById(R.id.number_3_textView);
    mNumber4TextView = mDialogView.findViewById(R.id.number_4_textView);
    mNumber5TextView = mDialogView.findViewById(R.id.number_5_textView);
    mNumber6TextView = mDialogView.findViewById(R.id.number_6_textView);
    ivLeft = mDialogView.findViewById(R.id.iv_pop_dismiss);
    tvTitle = mDialogView.findViewById(R.id.tv_pop_title);

    tvTitle.setText("请输入资金密码");

    mNumberViewList.add(mNumber1TextView);
    mNumberViewList.add(mNumber2TextView);
    mNumberViewList.add(mNumber3TextView);
    mNumberViewList.add(mNumber4TextView);
    mNumberViewList.add(mNumber5TextView);
    mNumberViewList.add(mNumber6TextView);

    mNumbersGridView = mDialogView.findViewById(R.id.numbers_gridView);
    mNumbersGridView.setAdapter(mNumberAdapter);
    mNumbersGridView.setOnItemClickListener(this);
    ivLeft.setOnClickListener(this);
  }

  @Override public void dismiss() {
    super.dismiss();
    instance = null;
    tmpContext = null;
  }

  public PassValidationDialogBuilder setCallBack(OnInputNumberCodeCallback callBack) {
    this.mCallback = callBack;
    return this;
  }

  @Override
  public void show() {
    super.show();
  }

  @Override public void onClick(View view) {
    switch (view.getId()) {
      case R.id.iv_pop_dismiss:
        dismiss();
        break;

      default:
        break;
    }
  }

  @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    if (position == NUMBER_BUTTON_CLEAR) {
      cleanNumber();
      return;
    }
    if (position == NUMBER_BUTTON_DELETE) {
      deleteNumber();
    } else {
      if (position == NUMBER_BUTTON_ZERO) {
        mNumberStack.push(0);
      } else {
        mNumberStack.push(++position);
      }
    }
    refreshNumberViews(mNumberStack);
    //input 6 numbers complete
    if (mNumberStack.size() == NUMBER_COUNT) {
      StringBuilder codeBuilder = new StringBuilder();
      for (int number : mNumberStack) {
        codeBuilder.append(number);
      }
      validation(codeBuilder.toString());
    }
  }

  /**
   * 验证密码，这里直接写在本地验证了
   */
  private void validation(String code) {
    if (null != mCallback) {
      mCallback.onSuccess(code);
    }
    dismiss();
  }

  /**
   * 返回输出的结果
   */
  public interface OnInputNumberCodeCallback {
    void onSuccess(String code);
  }

  /**
   * 清空mNumberStack的内容并刷新密码格
   */
  public void cleanNumber() {
    mNumberStack.clear();
    refreshNumberViews(mNumberStack);
  }

  /**
   * 删除密码位数
   */
  public void deleteNumber() {
    if (mNumberStack.empty() || mNumberStack.size() > NUMBER_COUNT) {
      return;
    }
    mNumberStack.pop();
  }

  /**
   * 刷新输入框显示
   */
  public void refreshNumberViews(Stack<Integer> mNumberStack) {

    for (int i = 0, size = mNumberViewList.size(); i < size; i++) {
      int numSize = mNumberStack.size();
      if (i < numSize) {
        if (mIsPassword) {
          mNumberViewList.get(i).setText(PASSWORD_NUMBER_SYMBOL);
        } else {
          mNumberViewList.get(i).setText(String.valueOf(mNumberStack.get(i)));
        }
      } else {
        mNumberViewList.get(i).setText("");
      }
    }
  }
}
